#include <Arduino.h>
#include <WiFi.h>

const char *ssid = "461";
const char *password = "20030717";

const IPAddress serverIP(192, 168, 31, 150); // 欲访问的服务端IP地址
uint16_t serverPort = 19810;				 // 服务端口号

WiFiClient client; // 声明一个ESP32客户端对象，用于与服务器进行连接

void WiFi_Connect()
{
	WiFi.begin(ssid, password);
	while (WiFi.status() != WL_CONNECTED)
	{
		delay(300);
		Serial.print(".");
	}
}

void setup()
{
	Serial.begin(115200);
	delay(100);

	WiFi.mode(WIFI_STA);
	WiFi.setSleep(false);

	Serial.print("Connecting.. ");

	WiFi_Connect();

	Serial.println("WiFi connected");

	Serial.println("IP address: ");
	Serial.println(WiFi.localIP());

	pinMode(0, OUTPUT);
}

void loop()
{
	Serial.println("尝试访问服务器");
	if (client.connect(serverIP, serverPort)) // 尝试访问目标地址
	{
		Serial.println("访问成功");
		client.print("Hello world!");					 // 向服务器发送数据
		while (client.connected() || client.available()) // 如果已连接或有收到的未读取的数据
		{
			if (client.available()) // 如果有数据可读取
			{
				String line = client.readStringUntil('\n'); // 读取数据到换行符
				if (line == "ON")
				{

					digitalWrite(0, LOW);
				}
				else if (line == "OFF")
				{

					digitalWrite(0, HIGH);
				}
			}
		}
		Serial.println("关闭当前连接");
		client.stop(); // 关闭客户端
	}
	else
	{
		Serial.println("访问失败");
		client.stop(); // 关闭客户端
	}
	delay(1000);
	delay(3000);
}